import {formatDate, verifyIdCard} from '@/tools/index'
import _deepclone from 'lodash/cloneDeep'
import {Api} from "@/api/index";
import {sessionStorage} from '@/common/cacheUtils.js';

export default {
    idCardValidator: (rule, value, callback) => {
        if (!verifyIdCard(value)) {
            callback('请填写正确的身份证号码');
        } else {
            callback()
        }
    },
    setQueryOrgName(data) {
        this.$set(this.dataToQuery, "companyName", data);
    },
    setQueryCompanyName(data) {
        this.$set(this.dataToQuery, 'companyId', data[data.length - 1])
    },
    setQueryCompanyId(data) {
        if (data && data instanceof Array && data.length > 0) {
            this.dataToQuery.companyId = data[data.length - 1];
        } else {
            this.dataToQuery.companyId = null;
        }
    },
    onSelectQueryDateRange(data) {
        if (data[0] === "" || data[1] === "") {
            this.dataToQuery.beginDate = null;
            this.dataToQuery.endDate = null;
        } else {
            this.dataToQuery.beginDate = data[0] + ' 00:00:00';
            this.dataToQuery.endDate = data[1] + ' 23:59:59';
        }
    },
    onSelectFieldQueryDateRange(data, filed) {
        if (data[0] === "" || data[1] === "") {
            this.dataToQuery[filed + 'From'] = null;
            this.dataToQuery[filed + 'To'] = null;
        } else {
            this.dataToQuery[filed + 'From'] = data[0] + ' 00:00:00';
            this.dataToQuery[filed + 'To'] = data[1] + ' 23:59:59';
        }
    },
    setCompanyId(data) {
        if (data && data instanceof Array && data.length > 0) {
            this.$set(this.dataToView, 'companyId', data[data.length - 1])
            // if(this.$refs.dialogForm) this.$refs.dialogForm.validateField('companyId')
        }
    },
    setCompanyName(data) {
        if (data) {
            this.dataToView.companyName = data;
            this.$refs.dialogForm.validateField('companyId')
        }
    },
    cascaderQueryDomIdChangeHandle(data, idField) {
        if (data && data instanceof Array && data.length > 0 && idField) {
            this.$set(this.dataToQuery, idField, data[data.length - 1])
        }
    },
    cascaderQueryDomNameChangeHandle(data, idField) {
        if (data && idField) {
            this.$set(this.dataToQuery, idField, data)
        }
    },
    cascaderDomIdChangeHandle(data, idField) {
        if (data && data instanceof Array && data.length > 0 && idField) {
            this.$set(this.dataToView, idField, data[data.length - 1])
        }
    },
    cascaderDomNameChangeHandle(data, idField) {
        if (data && idField) {
            this.$set(this.dataToView, idField, data)
        }
    },
    getSelectRows(rows) {
        this.deleteRows = rows;
    },
    batDelete() {
    },
    deleteDateAjax(params) {
        this.$Modal.confirm({
            title: '提示',
            content: '<p>确认删除此行数据？</p>',
            onOk: () => {
                let url = this.deleteUrl;
                this.$http.delete(url + '/' + params.row.id, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                        this.$Message.success('删除成功');
                        this.query()
                    } else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    }
                }).catch(e => {
                    this.$Message.error('删除失败' + e);
                })
            },
            onCancel: () => {
            }
        });
    },
    queryAjax() {
        this.pageStatus.loading = true
        let data = {
            startPage: this.pagedata.currentPage,
            size: this.pagedata.pageSize,
            conditions: this.dataToQuery
        };

        this.$http.post(this.queryUrl, data).then((res) => {
            if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
            }
            if (this.beforeEditDataTable instanceof Function) {
                this.dataTable = this.beforeEditDataTable(res.data.data.data)
            } else {
                this.dataTable = res.data.data.data;
            }
            this.pagedata.total = res.data.data.totalSize;
            this.pageStatus.loading = false
        }).catch(e => {
            this.$Message.error("数据获取失败")
            this.pageStatus.loading = false
        })
    },
    exportFormSubmit() {
        let token = sessionStorage('token').get('Authorization');
        this.dataToQuery.token = token
        this.dataToQuery.exportPerson = this.currentUser.userName;
        this.dataToQuery.exportDate = new Date();
        this.dataToQuery.exportPhone = this.currentUser.mobileNumber;
        // this.dataToQuery.companyName = this.currentUser.companyName;
        this.downloadTable({
            formData: this.dataToQuery,
            action: this.exportUrl,
            method: 'get'
        })
    },
    downloadTable({ formData, action = '',fileName=''}) {
        // this.$Spin.show({
        //     render: (h) => {
        //         return h('div', [
        //             h('Icon', {
        //                 'class': 'demo-spin-icon-load',
        //                 props: {
        //                     type: 'ios-loading',
        //                     size: 18
        //                 }
        //             }),
        //             h('div', 'Loading')
        //         ])
        //     }
        // });
        let data = {}
        for (let key in formData) {
            let value = formData[key]
            if (value instanceof Array) {
                data[key + '[]'] = value.toString()
            }
            if (value) {
                data[key] = value
            }
        }
        this.exportLoading = true;
        this.$http.get(action,{
            params: data,
            responseType: 'blob'
        }).then(res => {
            // this.$Spin.hide();
            this.exportLoading = false;
            const aLink = document.createElement("a");
            aLink.target = '_blank'
            let blob = new Blob([res.data], {
                type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
            });
            aLink.href = URL.createObjectURL(blob)
            if (!fileName) {
                let dis= res.headers.map['content-disposition']
                fileName=dis.toString().split('attachment;filename=')[1]
                fileName = decodeURIComponent(decodeURI(fileName))
            }
            aLink.download = fileName //标题
            aLink.click()
            document.body.appendChild(aLink)
        }).catch((r) => {
            console.error(r)
            this.$Spin.hide();
            this.$Message.error('下载文件出现错误，请联系管理员！')
        })
    },
    setDataPickerValue(key, value) {
        this.dataToView[key] = value
    },
    /**
     *
     * @param name form表单ref值
     * @param dateToSubmit form表单model对象
     * @param validateFieldArr 需要校验字段的prop 数组
     */
    submitAjaxValidateField(name, dateToSubmit,validateFieldArr) {
        if (this.pageStatus.sending) return
        if (validateFieldArr === undefined) {
            validateFieldArr = Object.keys(_deepclone(this.ruleCustom))
        }
        let _self = this;
        Promise.all(validateFieldArr.map(item => {
            return new Promise(function (resolve, reject) {
                _self.$refs[name].validateField(item, (error) => {
                    resolve(error)
                })
            });
        })).then((data) => {
            // data 里是各个字段的验证错误信息, 如果为空串则认为验证通过, 如果数组里全为空串则所有验证通过
            // 去除数组空值
            data = data.filter(item => item)
            if(!data.length){  //通过验证
                if (_self.rewriteSubmitAjax instanceof Function) {
                    _self.rewriteSubmitAjax(name, dateToSubmit)
                } else {
                    _self.submitAjax(name, dateToSubmit)
                }
            } else {  //验证不通过 暂时只提示一个
                _self.$Message.error(data[0]);
            }
        })
    },
    submitAjax(name, dateToSubmit) {
        if (this.pageStatus.sending) return
        this.$refs[name].validate((valid) => {
            if (valid) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要提交？</p>',
                    onOk: () => {
                        if (dateToSubmit === undefined) {
                            dateToSubmit = _deepclone(this.dataToView)
                        }
                        let url = this.mode === 'add' ? this.saveUrl : this.updateUrl;
                        // 月份转为日期
                        if (dateToSubmit.rptPeroid) {
                            dateToSubmit.rptPeroid = formatDate(dateToSubmit.rptPeroid, 'yyyy-MM-dd')
                        }
                        this.pageStatus.sending = true
                        let successHandle = (res) => {
                            if (res.data.status === 200) {
                                this.$Message.success(this.mode === 'add' ? '添加成功' : '修改成功');
                                this.dialogShow = false;
                                this.query()
                            } else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);
                            }
                            this.pageStatus.sending = false
                        }
                        let failedHandle = e => {
                            this.$Message.error(this.mode === 'add' ? '添加失败' : '修改失败')
                            this.pageStatus.sending = false
                        }
                        if (this.mode === 'add') {
                            this.$http.post(url, dateToSubmit).then(successHandle).catch(failedHandle)
                        } else {
                            this.$http.put(url, dateToSubmit).then(successHandle).catch(failedHandle)
                        }
                    },
                    onCancel: () => {
                    }
                });
            } else {
                this.$Message.error('请填报完整!');
            }
        })
    },
    addInfo() {
        this.dataToView = (this.createEmptyDataToAdd instanceof Function) ? this.createEmptyDataToAdd() : {};
        this.dataToView.id = this.get_uuid()
        this.dataToView.companyId = this.currentUser.companyId;
        this.dataToView.companyName = this.currentUser.companyName;
        this.dataToView.createUserName = this.currentUser.userName;
        this.dataToView.belongOrgId = this.currentUser.twoLevelOrgId;
        this.dataToView.belongOrgName = this.currentUser.twoLevelOrgName;
        this.dataToView.registrant = this.currentUser.userName;
        this.dataToView.registrantPhone = this.currentUser.mobileNumber;
        this.dataToView.registTime = new Date();
        this.dataToView.createUserId = this.currentUser.userId;
        this.dataToView.createOrgId = this.currentUser.orgInfo.orgId;
        this.dataToView.createDate = new Date();
        this.mode = 'add'
        this.dialogShow = true;

        setTimeout(()=>{
            this.dialogVisibleChangeHandele(this.dialogShow)
        },100)

        if (this.afterDataToAddInit instanceof Function) {
            this.afterDataToAddInit()
        }
    },
    pageChange(pageNum) {
        this.pagedata.currentPage = pageNum;
        this.queryAjax();
    },
    pageSizeChange(pageSize) {
        this.pagedata.pageSize = pageSize;
        this.queryAjax();
    },
    handleCancel() {
        this.dataToView = {};
        this.dialogShow = false
        this.query();
    },
    // 搜索条件
    switchQuery(flag, height) {
        if (!height) {
            height = 44;
        }
        this.switchFlag = flag;
        if (!this.switchFlag) {
            this.tableHeight = this.tableHeight + height;
        } else {
            this.tableHeight = this.tableHeight - height;
        }
    },
    getCodingSort(code) {
        return this.$http.get(Api.queryCodeDetailBySortId + '/' + code, {params: {}});
    },
    reset() {
        this.dataToQuery = {};
        if (this.$refs.queryOrgCascader) {
            this.$refs.queryOrgCascader.resetCurrentOrg();
        }
        if (this.$refs.queryOrgCascader1) {
            this.$refs.queryOrgCascader1.resetCurrentOrg();
        }
        this.pagedata.currentPage = 1
        this.query()
    },
    sortChange(data) {
        if (data.order === 'asc' || data.order === 'desc') {
            let order = data.key
            this.dataToQuery.dynamicSort = order + ' ' + data.order
            this.query()
        }
    },
    async editData(data) {
        if (this.beforeEditDialogOpen instanceof Function) {
            await this.beforeEditDialogOpen(data)
        }
        //修改页面
        this.mode = 'edit'
        let dataToView = _deepclone(data.row);
        this.dataToView = dataToView
        // this.dataToView.registrant = this.currentUser.userName;
        // this.dataToView.registrantPhone = this.currentUser.mobileNumber;
        // this.dataToView.registTime = new Date();
        if (this.afterDataToViewInit instanceof Function) {
            await this.afterDataToViewInit(dataToView)
        }
        this.dialogShow = true;
        setTimeout(()=>{
            if (this.editEcho instanceof Function) {
                //引用组件回显用
                this.editEcho()
            }
            this.dialogVisibleChangeHandele(this.dialogShow)
        },100)
    },
    async viewData(data) {
        if (this.beforeViewDialogOpen instanceof Function) {
            this.beforeViewDialogOpen(data)
        }
        // 查看页面
        this.mode = 'view'
        let dataToView = _deepclone(data.row);
        this.dataToView = dataToView

        if (this.afterDataToViewInit instanceof Function) {
            await this.afterDataToViewInit()
        }
        this.dialogShow = true;
        setTimeout(()=>{
            this.dialogVisibleChangeHandele(this.dialogShow)
        },100)

    },
    rowClassName(row, index) {
        if (row.id === '-1') {
            return 'table-summary-row';
        }
    },
    renderCellArea(h, params) {
        return h('span', this.areaCodeToAreaName(params.row.companyAddress))
    },
    renderCellCode(h, codeId, code) {
        return h('span', this.dictMap[code][codeId] && this.dictMap[code][codeId].codingName);
    },
    areaCodeToAreaName(codeStr){
        if(!codeStr || codeStr === "") return "";
        var arr = codeStr.split(',')
        var outArr = []
        arr.forEach(codingCodeId => {
            if (this.areaMap[codingCodeId]) {
                outArr.push(this.areaMap[codingCodeId].codingName)
            }
        })
        return outArr.join("·")
    },
    addressEditArr(areaTreeMap,companyAddressArr){
        let tempAreaTree = areaTreeMap['0']
        if (companyAddressArr.length > 0) {
            let sheng = tempAreaTree.find(i => i.value === companyAddressArr[0])
            if (areaTreeMap[sheng.value]) {
                sheng['children'] = areaTreeMap[sheng.value]
                let shengIndex = sheng['children'].indexOf(sheng)
                if (companyAddressArr.length > 1) {
                    let shi = sheng['children'].find(i1 => i1.value === companyAddressArr[1])
                    if (areaTreeMap[shi.value]) {
                        shi['children'] = areaTreeMap[shi.value]
                        let shiIndex = shi['children'].indexOf(shi)
                        if (companyAddressArr.length > 2) {
                            let xian = shi['children'].find(i2 => i2.value === companyAddressArr[2])
                            if (xian) {
                                let index = shi['children'].indexOf(xian)
                                delete xian['loading'];
                                this.$set(shi['children'], index, xian)
                            }
                        }
                        this.$set(shi['children'], shiIndex, shi)
                    } else {delete shi['loading'];}
                }
                this.$set(sheng['children'], shengIndex, sheng)
            } else {delete sheng['loading'];}
        }
        return tempAreaTree
    },
    areaTreeLoadData(item, callback){
        item.loading = true;
        setTimeout(() => {
            if (this.areaTreeMap[item.value]) {
                item.children= this.areaTreeMap[item.value];
                item.loading = false;
                callback();
            }else {
                item.loading = false;
                delete item['loading'];
            }
        },100);
    },
    areaTreeChange(data,companyAddress,value,selectedData){
        this.$set(data,companyAddress,value.join(','))
        let name = []
        selectedData.forEach(m=>name.push(m.label))
        this.$set(data,'companyAddressName',name.join('·'))
    },
    renderCellDate(h, params) {
        let key = params.column.key;
        if (!params.row[key]) return "";
        return h('span', formatDate(new Date(params.row[key]), "yyyy-MM-dd"))
    },
    renderCellMonth(h, params) {
        let key = params.column.key;
        if (!params.row[key]) return "";
        return h('span', formatDate(new Date(params.row[key]), "yyyy-MM"))
    },
    renderCellDateTime(h, params) {
        let key = params.column.key;
        if (!params.row[key]) return "";
        return h('span', formatDate(new Date(params.row[key]), "yyyy-MM-dd hh:mm:ss"))
    },
    renderCellDateHourTime(h, params) {
        let key = params.column.key;
        if (!params.row[key]) return "";
        return h('span', formatDate(new Date(params.row[key]), "yyyy-MM-dd hh:mm"))
    },
    renderViewDateHourTime(date) {
        if (!date) return "";
        return formatDate(new Date(date), "yyyy-MM-dd hh:mm");
    },
    renderViewDateTime(date) {
        if (!date) return "";
        return formatDate(new Date(date), "yyyy-MM-dd hh:mm:ss");
    },
    renderViewDate(date) {
        if (!date) return "";
        return formatDate(new Date(date), "yyyy-MM-dd");
    },
    renderViewMonth(date) {
        return formatDate(new Date(date), "yyyy-MM");
    },
    renderViewYear(date) {
        return formatDate(new Date(date), "yyyy");
    },
    setTableHeight(height) {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - (height || 145);
    },
    setSumTableHeight() {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 193;
    },
    // 弹出框mode标记
    modeTypeText() {
        return (this.mode === 'add' ? '新增' : (this.mode === 'edit' ? '编辑' : '查看'))
    },
    dialogVisibleChangeHandele(visible){
        // 设置 弹出框内 内容 最大高度，使内容出滚动条
        if (visible) {
            try{
                document.getElementsByClassName('limit-height-dialog')[0].getElementsByClassName('ivu-modal-body')[0].style.maxHeight = (window.innerHeight-140+'px')
            }catch (e) {

            }
        }
    },
    get_uuid() {
        let s = [];
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "-";

        let uuid = s.join("");
        let reg = new RegExp("-", "g");
        let a = uuid.replace(reg, "");
        return a;
    },
    // 生成组件公共字段
    // 操作
    getActionColumns(noRender) {
        return {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 160,
            align: 'center',
            render: (h, params) => {
                if (noRender instanceof Function && noRender(params)) {
                    return;
                }
                if (this.currentUser.loginId === this.Common.admin ||
                    this.currentUser.userId === params.row.createUserId  ||
                    this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined ||
                    this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
                    return h('div', [
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            style: {fontSize: '14px',},
                            on: {
                                click: () => {
                                    this.viewData(params);
                                }
                            }
                        }, '详情'),
                        h('Divider', {props: {type: 'vertical'}}, ''),
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            disabled: true,
                            style: {fontSize: '14px',},
                            on: {
                                click: () => {
                                    this.editData(params);
                                }
                            }
                        }, '修改'),
                        h('Divider', {props: {type: 'vertical'}}, ''),
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            style: {fontSize: '14px', color: 'red',},
                            on: {
                                click: () => {
                                    this.deleteData(params);
                                }
                            }
                        }, '删除')
                    ]);
                } else {
                    return h('div', [
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            style: {fontSize: '14px',},
                            on: {
                                click: () => {
                                    this.viewData(params);
                                }
                            }
                        }, '详情'),
                        h('Divider', {props: {type: 'vertical'}}, ''),
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            style: {fontSize: '14px', color: '#c5c8ce',}
                        }, '修改'),
                        h('Divider', {props: {type: 'vertical'}}, ''),
                        h('A', {
                            props: {type: 'primary', size: 'small'},
                            style: {fontSize: '14px', color: '#c5c8ce',}
                        }, '删除')
                    ]);
                }
            }
        }
    },
    // 公共字段
    createCommonDataField() {
        return {
            uploadListVisible:[],
            uploadListPercent:[],
            currentUser: JSON.parse(sessionStorage('userId').get('userId')),
            // 页面状态
            pageStatus: {
                loading: false,
                sending: false,
                deleting: false
            },
            // 搜索
            dataToQuery: {
                companyId: '',
                // companyName: JSON.parse(sessionStorage('userId').get('userId')).companyName,
            },
            searchedDataToQuery: {},
            // 表單
            switchFlag: false,
            pageSizeArray: [10, 20, 50],
            pagedata: {
                total: 0,
                pageSize: 10,
                currentPage: 1,
            },
            dataTable: [],
            tableHeight: 10,
            // 彈出框
            dataToView: {},
            mode: 'add',
            dialogShow: false,
            fileUrl: Api.interestedPartiesUserFile,
            downloadUrl: Api.downloadMongoFile,
            tempAreaTree: [],
            exportLoading: false,
        }
    },
    // 序号render
    indexColumnsRender(h, params){
        return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
    },
    indexColumnsRenderSum(h, params){
        if(params.index == 0) return h('span', "汇总");
        return h('span', params.index-1 + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
    },
    // dict list 转 map
    dictListToMap(arr, key = 'codingCodeId') {
        var map = {}
        arr.map(item => {
            map[item[key]] = item
        })
        return map
    },
    getModalTitle(title) {
        if (this.mode === 'view') {
            return title + "详情";
        } else {
            return title;
        }
    },
    arrayToInFormat(arr) {
        if (arr && arr.length == 0) return null;
        var str = '';
        arr.map(item => {
            str += "'" + item + "',";
        })
        return str.substr(0, str.length - 1);
    },
    async getFiles(filedName) {
        if(this.dataToView[filedName]) {
            let url = this.fileUrl + '/' + this.dataToView[filedName] + '/files/guideFile'
            await this.$http.get(url).then((res) => {
                if (res.data.result == "success") {
                    this.$set(this.dataToView, filedName + 'Files', res.data.data)
                    let index = 0;
                    res.data.data.forEach(item=>{
                        this.uploadListPercent[index]=0;
                        this.uploadListVisible[index] = false;
                        index++;
                    })
                }
            });
        }
    },
    beforeUpload(file, filedName) {
        let formData = new FormData();
        formData.append("files", file); // 文件对象
        let url = this.fileUrl + '/' + this.dataToView[filedName] + '/files/guideFile'
        this.$http.post(url, formData).then((res) => {
            if (res.data.result == "success") {
                this.$Message.info("文件上传成功")
                this.getFiles(filedName);
            }
        })
        return false
    },
    removeFile(id, filedName) {
        let url = this.fileUrl + '/file/' + id;
        this.$http.delete(url).then((res) => {
            this.getFiles(filedName)
        })
    },

    async getFiles1(filedName, type) {
        if(this.dataToView[filedName]) {
            let url = this.fileUrl + '/' + this.dataToView[filedName] + '/files/' + type.split('/')[0]
            await this.$http.get(url).then((res) => {
                if (res.data.result == "success") {
                    this.$set(this.dataToView, filedName + 'Files', res.data.data)
                    let index = 0;
                    res.data.data.forEach(item=>{
                        this.uploadListPercent[index]=0;
                        this.uploadListVisible[index] = false;
                        this.uploadListVisible[item.id] = false;
                        index++;
                    })
                }
            });
        }
    },
    beforeUpload1(file, filedName, type) {
        let formData = new FormData();
        formData.append("files", file); // 文件对象
        let url = this.fileUrl + '/' + this.dataToView[filedName] + '/files/'+type
        this.$http.post(url, formData).then((res) => {
            if (res.data.result == "success") {
                this.$Message.info("文件上传成功")
                this.getFiles1(filedName, type);
            }
        })
        return false
    },
    removeFile1(id, filedName, type) {
        let url = this.fileUrl + '/file/' + id;
        this.$http.delete(url).then((res) => {
            this.getFiles1(filedName, type)
        })
    },
    handleView (id) {
        let routeUrl = this.$router.resolve({
            path: "/imgDetails",
            query: {id:id}
        });
        window.open(routeUrl.href, '_blank');
    },
    downloadFile(file) {
        let url = this.fileUrl + '/file/' + file.id;
        this.$http.get(url, {
            responseType: 'blob'      //告诉服务器我们需要的响应格式
        }).then((res) => {
            const aLink = document.createElement("a");
            let blob = new Blob([res.data], {
                type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
            });
            aLink.href = URL.createObjectURL(blob)
            aLink.download = file.fileName //标题
            aLink.click()
            document.body.appendChild(aLink)
        })
    },
    downloadFiles(file,index) {
        let url = this.fileUrl + '/file/' + file.id;
        this.uploadListVisible[index] = true;
        this.uploadListVisible[file.id] = true;
        var _this = this;
        this.$http.get(url, {
            responseType: 'blob',      //告诉服务器我们需要的响应格式
            progress:function(e){
                _this.$set(_this.uploadListPercent,index, 100 * (e.loaded / e.total));
            }
        }).then((res) => {
            const aLink = document.createElement("a");
            let blob = new Blob([res.data], {
                type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
            });
            aLink.href = URL.createObjectURL(blob)
            aLink.download = file.fileName //标题
            aLink.click()
            document.body.appendChild(aLink)
        })
    },
    // 展开原生事件  点击左侧展收起
    onExpand(row, status){
        if(status){
            this.dataTable.splice()
            this.dataTable.filter((item, index)=>{
                if(item.id === row.id){
                    item._expanded = true;   //展开选中的行
                }else{
                    item._expanded = false;   //其他行关闭
                }
                return item;
            });
        }else{
            this.dataTable.splice()
            this.dataTable.map((item, index)=>{
                if(item.id === row.id){
                    item._expanded = false;   //展开选中的行
                }else{
                    item._expanded = false;   //其他行关闭
                }
                return item;
            });
        }
    },
    deleteDateById(id) {
        let _this = this;
        this.$Modal.confirm({
            title: '提示',
            content: '<p>确认删除此行数据？</p>',
            onOk: () => {
                let url = this.deleteUrl;
                this.$http.delete(url + '/' + id, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                        this.$Message.success('删除成功');
                        if (_this.deleteDataToView instanceof Function) {
                            _this.deleteDataToView()
                        }
                        this.query1()
                    } else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    }
                }).catch(e => {
                    this.$Message.error('删除失败' + e);
                })
            },
            onCancel: () => {
            }
        });
    },
    query1() {
        this.pageStatus.loading = true
        let data = {
            startPage: this.pagedata.currentPage,
            size: this.pagedata.pageSize,
            orgId: sessionStorage('userId').getObject('userId').companyId,
        };
        data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
        this.$http.get(this.queryUrl, {params: data}).then((res) => {
            if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
            }
            this.dataTable = res.data.data.data;
            this.pagedata.total = res.data.data.totalSize;
            this.pageStatus.loading = false
        }).catch(e => {
            this.$Message.error("数据获取失败")
            this.pageStatus.loading = false
        })
    },
    submitBase(name,dateToSubmit) {
        let _this = this;
        if (this.pageStatus.sending) return
        this.$refs[name].validate((valid) => {
            if (valid) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要提交？</p>',
                    onOk: () => {
                        if (dateToSubmit === undefined) {
                            dateToSubmit = _deepclone(this.dataToView)
                        }
                        let url = this.mode === 'add' ? this.saveUrl : this.updateUrl;
                        // 月份转为日期
                        if(dateToSubmit.rptPeroid) {
                            dateToSubmit.rptPeroid = formatDate(dateToSubmit.rptPeroid,'yyyy-MM-dd')
                        }
                        this.pageStatus.sending = true

                        let successHandle = (res) => {
                            if (res.data.status === 200) {
                                this.$Message.success(this.mode === 'add' ? '添加成功' : '修改成功');
                                this.dialogShow = false;
                                if (_this.submitToDataToView instanceof Function) {
                                    _this.submitToDataToView()
                                }
                                this.query1()
                            } else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);
                            }
                            this.pageStatus.sending = false
                        }
                        let failedHandle = e => {
                            this.$Message.error(this.mode === 'add' ? '添加失败' : '修改失败')
                            this.pageStatus.sending = false
                        }
                        if (this.mode === 'add'){
                            this.$http.post(url, dateToSubmit).then(successHandle).catch(failedHandle)
                        }else{
                            this.$http.put(url, dateToSubmit).then(successHandle).catch(failedHandle)
                        }
                    },
                    onCancel: () => {
                    }
                });
            } else {
                this.$Message.error('请填报完整!');
            }
        })
    },
    pageChange1(pageNum) {
        this.pagedata.currentPage = pageNum;
        this.query1();
    },
    pageSizeChange1(pageSize) {
        this.pagedata.pageSize = pageSize;
        this.query1();
    },
}

export function hasRole(user, roleId) {
    return user.userRole.find(obj => obj.roleId == roleId) != undefined;
}


